<template>
  <div class="app-container">
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="queryParams.keyword"
            placeholder="权益名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.rights_type" placeholder="权益类型" clearable>
            <el-option
              v-for="(label, value) in options.types"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" placeholder="状态" clearable>
            <el-option
              v-for="(label, value) in options.status"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增权益</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="name" label="权益名称" width="180" show-overflow-tooltip />
        <el-table-column prop="rights_type_text" label="权益类型" width="120" />
        <el-table-column prop="level_text" label="适用等级" width="120" />
        <el-table-column prop="use_times" label="使用次数" width="100">
          <template #default="scope">
            {{ scope.row.use_times === -1 ? '不限' : scope.row.use_times + '次' }}
          </template>
        </el-table-column>
        <el-table-column prop="valid_period" label="有效期" width="120">
          <template #default="scope">
            {{ scope.row.valid_period === -1 ? '永久' : scope.row.valid_period + '天' }}
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status_text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              :type="scope.row.status ? 'danger' : 'success'"
              link
              @click="handleStatus(scope.row)"
            >
              {{ scope.row.status ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增权益' : '编辑权益'"
      v-model="dialogVisible"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="权益名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权益名称" />
        </el-form-item>
        <el-form-item label="权益类型" prop="rights_type">
          <el-select v-model="form.rights_type" placeholder="请选择权益类型">
            <el-option
              v-for="(label, value) in options.types"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="适用等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择适用等级">
            <el-option
              v-for="(label, value) in options.levels"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="使用次数" prop="use_times">
          <el-input-number
            v-model="form.use_times"
            :min="-1"
            :precision="0"
            :step="1"
          />
          <span class="ml-2">次 (-1表示不限次数)</span>
        </el-form-item>
        <el-form-item label="有效期" prop="valid_period">
          <el-input-number
            v-model="form.valid_period"
            :min="-1"
            :precision="0"
            :step="1"
          />
          <span class="ml-2">天 (-1表示永久有效)</span>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="0"
            :precision="0"
            :step="1"
          />
          <span class="ml-2">数字越小越靠前</span>
        </el-form-item>
        <el-form-item label="权益说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权益说明"
          />
        </el-form-item>
        <el-form-item label="使用规则" prop="use_rules">
          <el-input
            v-model="form.use_rules"
            type="textarea"
            :rows="3"
            placeholder="请输入使用规则"
          />
        </el-form-item>
        <el-form-item label="注意事项" prop="notice">
          <el-input
            v-model="form.notice"
            type="textarea"
            :rows="3"
            placeholder="请输入注意事项"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="(label, value) in options.status"
              :key="value"
              :label="Number(value)"
            >{{ label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      title="权益详情"
      v-model="detailVisible"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="权益名称">{{ detail.name }}</el-descriptions-item>
        <el-descriptions-item label="权益类型">{{ detail.rights_type_text }}</el-descriptions-item>
        <el-descriptions-item label="适用等级">{{ detail.level_text }}</el-descriptions-item>
        <el-descriptions-item label="使用次数">{{ detail.use_times === -1 ? '不限' : detail.use_times + '次' }}</el-descriptions-item>
        <el-descriptions-item label="有效期">{{ detail.valid_period === -1 ? '永久' : detail.valid_period + '天' }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ detail.sort }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detail.status ? 'success' : 'danger'">
            {{ detail.status_text }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="权益说明" :span="2">{{ detail.description || '-' }}</el-descriptions-item>
        <el-descriptions-item label="使用规则" :span="2">{{ detail.use_rules || '-' }}</el-descriptions-item>
        <el-descriptions-item label="注意事项" :span="2">{{ detail.notice || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.created_at }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detail.updated_at }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  keyword: '',
  rights_type: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 选项数据
const options = reactive({
  types: {
    1: '优惠折扣',
    2: '专属服务',
    3: '增值服务',
    4: '特权礼遇',
    5: '其他'
  },
  levels: {},
  status: {
    1: '启用',
    0: '禁用'
  }
})

// 获取选项数据
const getOptions = async () => {
  try {
    const res = await request.get('/member-rights/options')
    options.levels = res.data.levels || {}
  } catch (error) {
    console.error('获取选项数据失败：', error)
  }
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/member-rights/list', {
      params: queryParams
    })
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取列表失败：', error)
  }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.rights_type = ''
  queryParams.status = ''
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

// 表单数据
const form = reactive({
  name: '',
  rights_type: '',
  level: '',
  use_times: -1,
  valid_period: -1,
  sort: 0,
  description: '',
  use_rules: '',
  notice: '',
  status: 1
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入权益名称', trigger: 'blur' },
    { max: 100, message: '权益名称最多100个字符', trigger: 'blur' }
  ],
  rights_type: [
    { required: true, message: '请选择权益类型', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择适用等级', trigger: 'change' }
  ],
  use_times: [
    { required: true, message: '请输入使用次数', trigger: 'blur' },
    { type: 'number', message: '使用次数必须为数字', trigger: 'blur' }
  ],
  valid_period: [
    { required: true, message: '请输入有效期', trigger: 'blur' },
    { type: 'number', message: '有效期必须为数字', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' },
    { type: 'number', min: 0, message: '排序不能小于0', trigger: 'blur' }
  ]
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = key === 'status' ? 1 : key === 'use_times' || key === 'valid_period' ? -1 : key === 'sort' ? 0 : ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  try {
    const res = await request.get(`/app/ky_black/admin/member-rights/${row.id}`)
    Object.assign(form, res.data)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败：', error)
  }
}

// 详情
const detailVisible = ref(false)
const detail = ref({})

const handleDetail = async (row) => {
  try {
    const res = await request.get(`/app/ky_black/admin/member-rights/${row.id}`)
    detail.value = res.data
    detailVisible.value = true
  } catch (error) {
    console.error('获取详情失败：', error)
  }
}

// 更改状态
const handleStatus = (row) => {
  const statusText = row.status ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确认要${statusText}该权益吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.post('/app/ky_black/admin/member-rights/status', {
        id: row.id,
        status: row.status ? 0 : 1
      })
      ElMessage.success(`${statusText}成功`)
      getList()
    } catch (error) {
      console.error('更改状态失败：', error)
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await request.post('/app/ky_black/admin/member-rights', form)
          ElMessage.success('添加成功')
        } else {
          await request.put(`/app/ky_black/admin/member-rights/${form.id}`, form)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败：', error)
      }
    }
  })
}

// 初始化
onMounted(() => {
  getOptions()
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .table-wrapper {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.ml-2 {
  margin-left: 8px;
}
</style> 